package com.bianguo.zsd.SpringBootDemo.controller;

import com.bianguo.zsd.SpringBootDemo.bean.BaseEntity;
import com.bianguo.zsd.SpringBootDemo.bean.StrBean;
import com.bianguo.zsd.SpringBootDemo.bean.User;
import com.bianguo.zsd.SpringBootDemo.dao.UserDao;
import com.bianguo.zsd.SpringBootDemo.enums.ResultEnum;
import com.bianguo.zsd.SpringBootDemo.exception.GlobalException;
import com.bianguo.zsd.SpringBootDemo.repository.UserRepository;
import com.bianguo.zsd.SpringBootDemo.utils.ResultUtils;
import com.bianguo.zsd.SpringBootDemo.utils.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private final UserRepository userRepository;
    //    @Autowired
//    private UserService userService;
    @Autowired
    private UserDao userDao;

    @Autowired
    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
        BindingResult result;
    }

    @PostMapping("save")
    public BaseEntity<User> save(@RequestBody Map<String, String> reqMap) {
        String name = reqMap.get("name");
        BaseEntity<User> baseEntity = new BaseEntity();
        User user = new User();
        user.setUsername(name);
        user.setToken(TextUtils.getUUID());
        if (userRepository.save(user)) {
            baseEntity.setStatus(200);
            baseEntity.setMsg("用户保存成功");
            baseEntity.setData(user);
            System.out.printf("用户对象: %s 保存成功! \n", user);
        } else {
            baseEntity.setStatus(0);
            baseEntity.setMsg("用户保存失败");
        }
        return baseEntity;
    }

    @GetMapping("findAll")
    public BaseEntity<Collection<User>> findUserAll() {
        BaseEntity<Collection<User>> baseEntity = new BaseEntity<>();
        Collection<User> users = userRepository.findAll();
        baseEntity.setStatus(200);
        baseEntity.setMsg("获取成功");
        baseEntity.setData(users);
        return baseEntity;
    }

    @GetMapping("find/user/all")
    public BaseEntity<ArrayList<User>> getUsers() {
        BaseEntity<ArrayList<User>> baseEntity = new BaseEntity<>();
//        ArrayList<User> users = userService.getUsers();
        ArrayList<User> users = userDao.queryUsers();
        baseEntity.setStatus(200);
        baseEntity.setMsg("获取成功");
        baseEntity.setData(users);
        return baseEntity;
    }

    @PostMapping(value = {"find/user/by/id"}, produces = {"application/json;charset=utf-8"})
    public BaseEntity<User> getUserById(@RequestBody Map<String, Integer> reqMap) {
        BaseEntity<User> baseEntity = new BaseEntity<>();
//        User user = userService.getUserById(reqMap.get("id"));
        User user = userDao.queryUserById(reqMap.get("id"));
        baseEntity.setData(user);
        baseEntity.setMsg("获取成功");
        baseEntity.setStatus(200);
        return baseEntity;
    }

    @PostMapping("insert")
    public BaseEntity<User> insertUser(@RequestBody Map<String, String> reqMap) {
        BaseEntity<User> baseEntity = new BaseEntity<>();
        User user = new User();
        user.setPhoneNumber(reqMap.get("phoneNumber"));
        user.setPassword(reqMap.get("password"));
        user.setToken(TextUtils.getUUID());
        userDao.insertUser(user);
        baseEntity.setData(user);
        baseEntity.setMsg("获取成功");
        baseEntity.setStatus(200);
        return baseEntity;
    }

    @PostMapping("update")
    @Transactional(propagation = Propagation.REQUIRED)
    public BaseEntity<User> updateUser(@RequestBody Map<String, Object> reqMap) {
        int id = (Integer) reqMap.get("id");
        User user = userDao.queryUserById(id);
        if (user == null) {
            throw new GlobalException(ResultEnum.USER_ERROR);
        }
        String token = (String) reqMap.get("token");
        if (TextUtils.isEmpty(token)) {
            throw new GlobalException(ResultEnum.ACCOUNT_EXCEPTION);
        }
        if (!token.equals(user.getToken())) {
            throw new GlobalException(ResultEnum.LOGIN_OTHER);
        }
        String username = (String) reqMap.get("username");
        String password = (String) reqMap.get("password");
        String phoneNumber = (String) reqMap.get("phoneNumber");
        String address = (String) reqMap.get("address");
        String avatar = (String) reqMap.get("avatar");
        if (!TextUtils.isEmpty(username)) {
            user.setUsername(username);
        }
        if (!TextUtils.isEmpty(password)) {
            user.setPassword(password);
        }
        if (!TextUtils.isEmpty(phoneNumber)) {
            user.setPhoneNumber(phoneNumber);
        }
        if (!TextUtils.isEmpty(address)) {
            user.setAddress(address);
        }
        if (!TextUtils.isEmpty(avatar)) {
            user.setAvatar(avatar);
        }
        userDao.updateUser(user);
        user.setPassword(null);
        return ResultUtils.success(user);
    }

    @PostMapping("login")
    public BaseEntity<User> login(@RequestBody Map<String, String> reqMap) {
        String phoneNumber = reqMap.get("phoneNumber");
        if (TextUtils.isEmpty(phoneNumber)) {
            throw new GlobalException(ResultEnum.USER_ERROR);
        }
        String password = reqMap.get("password");
        if (TextUtils.isEmpty(password)) {
            throw new GlobalException(ResultEnum.USER_ERROR);
        }
        User user = userDao.login(phoneNumber, password);
        if (user == null) {
            throw new GlobalException(ResultEnum.USER_ERROR);
        }
        user.setToken(TextUtils.getUUID());
        return ResultUtils.success(user);
    }

    @PostMapping("upload")
    public BaseEntity<StrBean> upload(@RequestPart("img") FilePart filePart) {
        logger.info("fileName = {}", filePart.filename());
        StrBean strBean = new StrBean();
        strBean.setResult(filePart.filename());
        return ResultUtils.success(strBean);
    }
}
